import { memDeptField, memDeptFieldMove, memDeptFieldRemove, memDeptFieldUpdate } from "@/services/aigcUser";
import { ButtonGroup } from "@/utils/CommonComponent";
import { Button, Card, Checkbox, Form, Input, Modal, Select, Table, message } from "antd";
import React from "react";

class FieldPage extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      list:[],
      loading:false,
      addTitle:"",
      addVisible:false,
      currentField:null,
      sortVisible:false,
      sortLoading:false,
      sortList:[]
    }
  }

  componentDidMount(){
    this.getFields()
  }

  getFields = () => {
    this.setState({
      loading:false
    },async () => {
      const res = await memDeptField()
      const data = res ? res : []
      const list = [
        {
          showName:"基础信息",
          className:"baseFields",
          children:data.filter(item => item.type == 0),
          flag:"root"
        },
        {
          showName:"自定义字段",
          className:"customFields",
          children:data.filter(item => item.type == 1),
          flag:"root"
        }
      ]
      this.setState({
        list,
        loading:false
      })
    })
  }

  openAddField = row => {
    this.setState({
      currentField:row,
      addVisible:true,
      addTitle:row ? '配置字段' : '新增字段'
    },() => {
      if(row){
        this.props.form.setFieldsValue({
          showName:row.showName,
          dockField:row.dockField
        })
      }
    })
  }

  cancelAddField = () => {
    this.setState({
      addVisible:false,
      currentField:null
    },() => {
      this.props.form.resetFields()
    })
  }

  okAddField = () => {
    this.props.form.validateFields((error,values) =>  {
      if(!error){
        this.handleOk(values)
      }
    })
  }

  handleOk = async values => {
    const { currentField } = this.state;
    let obj = {
      showName:values.showName,
      dockField:values.dockField
    }
    if(currentField){
      obj = {...currentField,...obj}
    }else{
      obj = {...values,type:1,enabled:false}
    }
    const res = await memDeptFieldUpdate(obj)
    if(res.code == -1){}else{
      message.info(res.message)
      this.cancelAddField()
      this.getFields()
    }
  }

  removeItemConfirm = (id) => {
    Modal.confirm({
      title:"是否确定要删除？",
      okText:"确定",
      cancelText:"取消",
      okType:"danger",
      onOk:() => {
        this.doItemConfirm(id)
      }
    })
  }

  doItemConfirm = async id => {
    const res = await memDeptFieldRemove({id})
    message.info(res.message)
    this.getFields()
  }

  changeUse = async row => {
    const res = await memDeptFieldUpdate({...row,enabled:!row.enabled})
    message.info(res.message)
    this.getFields()
  }

  backData = () => {
    const { history } = this.props;
    history.push({ pathname: '/membersAndDepartments',query:{} })
  }

  openSortField = () => {
    this.setState({
      sortVisible:true
    },() => {
      this.getSortList()
    })
  }

  getSortList = () => {
    this.setState({
      sortLoading:true
    },async () => {
      const res = await memDeptField({enabled:true})
      this.setState({
        sortList:res ? res : [],
        sortLoading:false
      })
    })
  }

  upDown = async (row,targetIndex) => {
    const { sortList } = this.state;
    const res = await memDeptFieldMove({source:row.id,target:sortList[targetIndex].id})
    message.info(res.message)
    this.getSortList()
  }

  render(){
    const { list,loading,addTitle,addVisible,currentField,sortList,sortLoading,sortVisible } = this.state;
    const { form:{getFieldDecorator} } = this.props;
    const formItemLayout = {
			labelCol: { span: 5 },
			wrapperCol: { span: 19 },
		};
    const columns = [
      {
        title:"显示名称",
        dataIndex:"showName",
        width:200,
      },
      {
        title:"字段",
        dataIndex:"dockField",
        width:200,
        render:(dockField,row) => {
          return row.flag ? '' : dockField
        }
      },
      {
        title:"类型",
        dataIndex:"type",
        width:200,
        render:(type,row) => {
          return row.flag ? '' : type == 0 ? '基础属性' : '自定义属性'
        }
      },
      {
        title:"选用",
        dataIndex:"",
        width:200,
        render:(row) => {
          {
           return row.flag ? '' : (
              <div>
                <ButtonGroup 
                  title="配置"
                  group="edit-table"
                  handleClick={() => this.openAddField(row)}
                />
                {
                  row.type == 1 ? (
                    <ButtonGroup 
                      title="删除"
                      group="delete-table"
                      handleClick={() => this.removeItemConfirm(row.id)}
                    />
                  ) : ''
                }
                <Checkbox checked={row.enabled} onChange={() => this.changeUse(row)}>使用</Checkbox>
                
              </div>
            )
          }
          
        }
      }
    ]
    const sortColumns = [
      {
        title:"显示名称",
        dataIndex:"showName",
        width:200,
        align:"center"
      },
      {
        title:"操作",
        align:"center",
        render:(item,row,index) => {
          return (
            <div>
              <Button 
                icon="arrow-up" 
                size="small" 
                style={{marginRight:8,opacity:index == 0 ? '0' : '1',pointerEvents:index == 0 ? 'none' : 'all'}}
                onClick={() => this.upDown(row,index - 1)}
              >上移</Button>
              <Button 
                icon="arrow-down" 
                size="small"
                style={{marginRight:8,opacity:index == sortList.length - 1 ? '0' : '1',pointerEvents:index == sortList.length - 1 ? 'none' : 'all'}}
                onClick={() => this.upDown(row,index + 1)}
              >下移</Button>
            </div>
          )
        }
      }
    ]
    return(
      <Card style={{height:'100%'}}>
        <div style={{marginBottom:24}}>
          <ButtonGroup 
            title="新增字段"
            group="add"
            handleClick={() => this.openAddField()}
          />
          <ButtonGroup 
            title="字段排序"
            group="sort"
            handleClick={() => this.openSortField()}
          />
          <Button onClick={() => this.backData()}>返回组织</Button>
        </div>
        <div style={{marginBottom:24}}>管理成员的系统预置字段，并添加自定义字段拓展成员、部门等信息，成员字段可应用于客户端名片页、搜索、入职登记表等位置</div>

        <Table 
          columns={columns}
          dataSource={list}
          loading={loading}
          rowKey={'className'}
          pagination={false}
        />

        <Modal
          title={addTitle}
          visible={addVisible}
          onCancel={this.cancelAddField}
          onOk={this.okAddField}
        >
          <Form {...formItemLayout}>
            <Form.Item label="显示名称">
              {
                getFieldDecorator("showName",{rules:[{required:true,message:"请输入显示名称"}]})(
                  <Input />
                )
              }
            </Form.Item>
            <Form.Item label="字段ID">
              {
                getFieldDecorator("dockField",{rules:[{required:true,message:"请输入字段ID"}]})(
                  <Input />
                )
              }
            </Form.Item>
            {
              currentField ? '' : (
                <Form.Item label="字段类型">
                  {
                    getFieldDecorator("fieldType",{rules:[{required:true,message:"请选择字段类型"}]})(
                      <Select>
                        <Select.Option value={0}>文本</Select.Option>
                        <Select.Option value={1}>数字</Select.Option>
                      </Select>
                    )
                  }
                </Form.Item>
              )
            }
            
          </Form>
        </Modal>

        <Modal
          title='使用字段排序'
          visible={sortVisible}
          onCancel={() => this.setState({sortVisible:false})}
          footer={null}
        >
            <Table 
              columns={sortColumns}
              dataSource={sortList}
              loading={sortLoading}
              pagination={false}
              scroll={{y:600}}
            />
        </Modal>
      </Card>
    )
  }
}

export default Form.create()(FieldPage)